var express = require('express')
var router = express.Router()
const { getAll, getById, exec } = require('../db/index')

// GET /users?page = 1 & size = 5
router.get('/', async (req, res) => {
  // 解析请求参数
  const { page = 1, size = 5 } = req.query

  let sql = `select count(*) as total from category`
  let { total } = await getById(sql)

  // 偏移量 = (page - 1) * size
  let offset = (page - 1) * size
  // 操作数据库
  sql = `select id, tag from category limit ${offset},${size}`
  const data = await getAll(sql)

  res.send({
    code: 0,
    message: '获取所有分类成功',
    result: {
      total,
      data,
    },
  })
})

// 根据id获取单个分类
router.get('/:id', async (req, res) => {
  const { id } = req.params

  let sql = `select * from category where id=${id}`
  console.log(sql)

  const data = await getById(sql)
  const { tag } = data
  res.send({
    code: 0,
    message: '获取单个用户成功',
    result: {
      tag,
    },
  })
})

// 新增
router.post('/', async (req, res) => {
  console.log(req.body)
  // 解析请求参数
  const { category } = req.body

  let sql = `insert into category (tag) values('${category}')`
  console.log(sql)
  //return
  const { insertId } = await exec(sql)

  res.send({
    code: 0,
    id: insertId,
    message: '添加分类成功',
  })
})

router.put('/:id', async (req, res) => {
  // const { id } = req.params
  const { id, category } = req.body

  let sql = `update category set tag='${category}' where id=${id}`
  console.log(sql)

  await exec(sql)

  res.send({
    code: 0,
    message: '修改成功',
    result: {
      id,
      category,
    },
  })
})

module.exports = router
